# TODO: 导入必要的库和模块
from sklearn.datasets import load_digits  
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier 
import joblib
from tqdm import tqdm 
# TODO: 加载数字数据集
digits = load_digits()
X = digits.data
y = digits.target
# TODO: 将数据集划分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, 
                                                    shuffle=True, stratify=y)
# TODO: 初始化变量以存储最佳准确率，相应的k值和最佳knn模型
best_accuracy = 0
best_k = 6  # 假设k值为6是最佳的
best_knn_model = None
# TODO: 初始化一个列表以存储每个k值的准确率
accuracies = []
# TODO: 尝试从1到40的k值，对于每个k值，训练knn模型，保存最佳准确率，k值和knn模型
for k in tqdm(range(6, 7), desc="Training KNN models"):  # 使用tqdm显示进度条
    knn = KNeighborsClassifier(n_neighbors=k)
    knn.fit(X_train, y_train)
    accuracy = knn.score(X_test, y_test)
    accuracies.append(accuracy)
    if k == 6:
        print(f"k值为6时的准确率: {accuracy}")  
    if accuracy > best_accuracy:
        best_accuracy = accuracy
        best_k = k
        best_knn_model = knn
# TODO: 将最佳KNN模型保存到二进制文件
joblib.dump(best_knn_model, 'best_knn_model.pkl')
# TODO: 打印最佳准确率和相应的k值
print(f"最佳准确率: {best_accuracy}")
print(f"相应的k值: {best_k}")
